﻿using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.TestFunc.测试代码
{

    public static class DITest5
    {
        public interface IAccount { }
        public interface IMessage { }
        public interface ITool { }

        public class Base:IDisposable
        {
            public Base()
            {
                Console.WriteLine($"创建：{GetType().Name}");
            }
            public void Dispose()
            {
                Console.WriteLine($"释放：{GetType().Name}");
            }
        }


        public class Account : Base, IAccount { }
        public class Message : Base, IMessage { }
        public class Tool : Base, ITool { }
        public static void Run()
        {
            var root = new ServiceCollection()
            .AddTransient<IAccount, Account>()
            .AddScoped<IMessage, Message>()
            .AddSingleton<ITool, Tool>()
            .BuildServiceProvider();

            var child1 = root.CreateScope().ServiceProvider;
            var child2 = root.CreateScope().ServiceProvider;

            GetService<IAccount>(child1);
            GetService<IMessage>(child1);
            GetService<ITool>(child1);
            Console.WriteLine();
            GetService<IAccount>(child2);
            GetService<IMessage>(child2);
            GetService<ITool>(child2);
            Console.ReadKey();
        }

        public static void GetService<T>(IServiceProvider provider)
        {
            provider.GetService<T>();
            provider.GetService<T>();
        }
    }
}
